package com.neo.service;

import com.neo.util.DjsStringUtil;
import com.neo.util.ReadFromFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 处理债权关系文件，生成jx_invest_record表数据，标的号需关联jx_invest_project
 * Created by wx on 2017/12/19.
 */
@Service
public class TransferInvRecordService {
    protected static Logger logger = LoggerFactory.getLogger(TransferInvRecordService.class);

    @Autowired
    private JdbcTemplate jdbcTemplate;

    private static String recordTableColumnFromFile = "USERNAME,INV_ACC_ID,BOR_ACC_ID,INV_ACCOUNT_ID,BOR_ACCOUNT_ID," +
            "PRODUCT_ID,ORDER_ID,AUTH_CODE,PRODUCT_NAME,PRODUCT_TYPE,YEAR_RATE,EXPECTED_INCOME,INV_AMOUNT,INV_DAY," +
            "INV_DATE,INV_STATUS,INV_SOURCE,OUT,INTEREST_START_DATE,INTEREST_END_DATE,INTEREST_NEXT_DATE," +
            "SETTLEMENT_NEXT_DATE,TAKE_BACK_DAYS,REMAINDER_DAYS,TAKE_BACK_PRINCIPAL,TAKE_BACK_INTEREST,WAIT_BACK_PRINCIPAL," +
            "WAIT_BACK_INTEREST,TRANSFER_AMOUNT,TRANSFER_TIME,USER_COUPON_ID,COUPON_RATE,COUPON_DAY,COUPON_EXPIRE_DATE," +
            "USER_REDPACKET_ID,REDPACKET_AMOUNT,REDPACKET_SECOND_TYPE,REPEAT_STATUS,RECORD_PACKAGE_ID";
    //todo  读取文件内容入库
    //todo  文件内容生成即信请求文件
    //todo  根据返回文件修改已入库的内容

    /**
     * todo 可加入fileName参数，用于接收请求直接处理
     */
    public void insertCreditRecord() {
        List listCsv = ReadFromFile.readFileByLinesGbk(DjsStringUtil.PLAN_FILE_PATH);
        for (int i = 1; i < listCsv.size(); i++) {
            String[] s = (String[]) listCsv.get(i);
            String[] keys = recordTableColumnFromFile.split(",");
            Map<String, String> datas = getRecordByStringArgs(keys, s);
            String sql = assemblingSql(datas);
            if (!sql.equals("error")) {
                jdbcTemplate.update(sql);
            }
            logger.info("res====" + i + "/" + listCsv.size());
        }
    }


    //拼装sql
    public String assemblingSql(Map<String, String> datas) {
        StringBuffer sql = new StringBuffer(" INSERT INTO jx_inv_record ");
        Boolean assembFlag = false;
        StringBuffer columnSql = new StringBuffer("(");
        StringBuffer valuesSql = new StringBuffer("values(");
        sql.append("(");
        for (String columns : datas.keySet()) {
            if (assembFlag) {
                columnSql.append(",");
                valuesSql.append(",");
            }
            columnSql.append(columns);
            valuesSql.append(datas.get(columns));
            assembFlag = true;
        }
        if (!assembFlag) {
            return "error";
        }
        columnSql.append(") ");
        valuesSql.append(") ");
        sql.append(columnSql).append(valuesSql);
        return sql.toString();
    }


    /**
     * keys简单的按照数据库字段先后顺序处理（不合理）
     * <p/>
     * 粗糙，目前能想到的最简单的封装方式，可能需要重写
     */
    private Map<String, String> getRecordByStringArgs(String[] keys, String[] args) {
        Map<String, String> datas = new HashMap<>();
        for (int i = 0; i < args.length; i++) {
            datas.put(keys[i], args[i]);
        }
        //删除文件计息方式字段数据，数据库没有该字段
        if (datas.containsKey("OUT")) {
            datas.remove("OUT");
        }
        return datas;
    }


    public static void main(String[] agrs) {
        Map<String,String> datas = new HashMap<>();
        datas.put("test","123");
        datas.put("test2","456");
        datas.put("test3","789");
        datas.put("test4","11");
        datas.put("test5","22");
        StringBuffer sql = new StringBuffer(" INSERT INTO jx_inv_record ");
        Boolean assembFlag = false;
        StringBuffer columnSql = new StringBuffer("(");
        StringBuffer valuesSql = new StringBuffer("values(");
        for (String columns : datas.keySet()){
            if (assembFlag){
                columnSql.append(",");
                valuesSql.append(",");
            }
            columnSql.append(columns);
            valuesSql.append(datas.get(columns));
            assembFlag = true;
        }

        columnSql.append(") ");
        valuesSql.append(") ");
        sql.append(columnSql).append(valuesSql);
        if (!assembFlag){
            sql = new StringBuffer("error");
        }
        System.out.println(sql);
    }

}
